package myjava.h_exception;

/**
 * @Auther: cty
 * @Date: 2019/11/7 下午10:50
 * @Description: myjava.h_exception  测试常见runtime exception  运行时处理的异常
 * @version: 1.0
 */
public class A_Runtime {
    public static void main(String[] args) {

        System.out.println("异常1——ArithmeticException");  //算术异常，如/ by zero
        int a = 0;
        int b = 1;
//        System.out.println(b/a);  //ArithmeticException，运行到这里程序中断！！！
        //异常解决
        if(a!=0){
            System.out.println(b/a);
        }
        System.out.println("#############################################end");

        System.out.println("异常2——NullPointerException");
        String str = null;

        //System.out.println(str.length());  //NullPointerException
        //异常解决
        if(str!=null){
            System.out.println(str.length());
        }
        System.out.println("#############################################end");

        System.out.println("异常3——ClassCastException");  //发生在类型转换时
        class Animal{
        }
        class Dog extends Animal{
        }
        class Cat extends Animal{
        }
        Animal c =new Dog();

        //Cat d =(Cat)c;  //ClassCastException
        //异常解决
        if(c instanceof Cat){
            Cat d =(Cat)c;
        }
        System.out.println("#############################################end");

        System.out.println("异常4——ArrayIndexOutOfBoundsException");  //数组下标越界异常
        int[] arr = new int[5];

        //System.out.println(arr[5]);  //ArrayIndexOutOfBoundsException
        //异常解决
        int e = 5;
        if(e<arr.length){
            System.out.println(arr[5]);
        }
        System.out.println("#############################################end");

        System.out.println("异常5——NumberFormatException");  //将字符串转成包装类时遇到的错误
        String str1 = "1234abcd";
        System.out.println(Integer.parseInt(str1));  //NumberFormatException
    }
}
